package com.security.springsecurity.config;

import com.security.springsecurity.service.CustomUserService;
import com.security.springsecurity.service.MyFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyFilterSecurityInterceptor myFilterSecurityInterceptor;

    @Autowired
    private CustomUserService customUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService).passwordEncoder(new BCryptPasswordEncoder()); //user Details Service验证
    }

    // 忽略拦截
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 基于用户角色测试用放行接口
//        web.ignoring().antMatchers("/admin/look");
        // 放行静态资源
        web.ignoring().antMatchers("/css/**","/vendors/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
        // 开启登录配置
        .authorizeRequests()
        // 表示访问 /admin 这个接口，需要具备 admin 这个角色
        // .antMatchers("/admin/**").hasRole("ADMIN")
        // 表示剩余的其他接口，登录之后就能访问
        .anyRequest().authenticated()
        .and()
        .formLogin()
        // 定义登录页面，未登录时，访问一个需要登录之后才能访问的接口，会自动跳转到该页面
        .loginPage("/login")
        // 访问指定页面，用户未登入，跳转至登入页面，如果登入成功，跳转至用户访问指定页面，用户访问登入页面，默认的跳转页面
        .defaultSuccessUrl("/")
        .failureUrl("/login?error")
        // 和表单登录相关的接口统统都直接通过
        .permitAll()
        .and()
        .logout()
        .permitAll();

        // 自定义拦截器
        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
    }
}
